from flask import Flask, jsonify, request
import pymysql
import logging

app = Flask(__name__)

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 数据库连接参数
# 本地测试数据库
DB_CONFIG_local = {
    'host': '127.0.0.1',
    'port': 13306,  # 指定端口号为13306
    'user': 'root',
    'password': 'abc123',
    'db': 'rvsystem_dfn',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

DB_CONFIG_TEST = {
    'host': '172.28.169.1',
    'port': 3306,  # 指定端口号为13306
    'user': 'nissan_user_telenet',
    'password': 'NAkqxt#37ks',
    'db': 'nissan_to_unicdata',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}




def get_db_connection():
    """
    创建并返回数据库连接
    """
    try:
        connection = pymysql.connect(**DB_CONFIG_TEST)
        logger.info("数据库连接成功")
        return connection
    except Exception as e:
        logger.error(f"数据库连接失败: {str(e)}")
        raise


@app.route('/query_vehicle_config', methods=['GET'])
def query_vehicle_config():
    """
    查询车型明细数据
    """
    try:
        connection = get_db_connection()
        with connection.cursor() as cursor:
            sql = "SELECT * FROM unicdata_vehicle_config WHERE transferstatus in (1,2)"
            cursor.execute(sql)
            result = cursor.fetchall()
        connection.close()
        return jsonify({"status": "success", "code": 200, "data": result}), 200
    except Exception as e:
        logger.error(f"查询车型明细数据失败: {str(e)}")
        return jsonify({"status": "error", "code": 500, "message": str(e)}), 500


@app.route('/update_vehicle_config', methods=['POST'])
def update_vehicle_config():
    """
    修改车型明细状态
    """
    try:
        id_list = request.json.get('id_list', [])

        # 如果ID列表为空，直接返回成功
        if not id_list:
            logger.info("ID列表为空，无需修改")
            return jsonify({"status": "success", "code": 200, "message": "无需修改"}), 200

        # ID列表不为空，执行更新操作
        connection = get_db_connection()
        with connection.cursor() as cursor:
            placeholders = ', '.join(['%s'] * len(id_list))
            sql = f"UPDATE unicdata_vehicle_config SET transferstatus = 3 WHERE id in ({placeholders})"
            cursor.execute(sql, id_list)

        connection.commit()
        connection.close()

        logger.info(f"成功更新 {cursor.rowcount} 条车型明细记录")
        return jsonify({"status": "success", "code": 200, "data": cursor.rowcount}), 200
    except Exception as e:
        logger.error(f"修改车型明细状态失败: {str(e)}")
        return jsonify({"status": "error", "code": 200, "message": str(e)}), 500


@app.route('/query_vehicle_basic', methods=['GET'])
def query_vehicle_basic():
    """
    查询车型数据
    """
    try:
        connection = get_db_connection()
        with connection.cursor() as cursor:
            sql = "SELECT * FROM unicdata_vehicle_basic WHERE transferstatus in (1,2)"
            cursor.execute(sql)
            result = cursor.fetchall()
        connection.close()
        return jsonify({"status": "success", "code": 200, "data": result}), 200
    except Exception as e:
        logger.error(f"查询车型数据失败: {str(e)}")
        return jsonify({"status": "error", "code": 200, "message": str(e)}), 500


@app.route('/update_vehicle_basic', methods=['POST'])
def update_vehicle_basic():
    """
    修改车型状态
    """
    try:
        id_list = request.json.get('id_list', [])

        # 如果ID列表为空，直接返回成功
        if not id_list:
            logger.info("ID列表为空，无需修改")
            return jsonify({"status": "success", "code": 200, "message": "无需修改"}), 200

        # ID列表不为空，执行更新操作
        connection = get_db_connection()
        with connection.cursor() as cursor:
            placeholders = ', '.join(['%s'] * len(id_list))
            sql = f"UPDATE unicdata_vehicle_basic SET transferstatus = 3 WHERE id in ({placeholders})"
            cursor.execute(sql, id_list)

        connection.commit()
        connection.close()

        logger.info(f"成功更新 {cursor.rowcount} 条车型记录")
        return jsonify({"status": "success", "code": 200, "data": cursor.rowcount}), 200
    except Exception as e:
        logger.error(f"修改车型状态失败: {str(e)}")
        return jsonify({"status": "error", "code": 200, "message": str(e)}), 500


if __name__ == '__main__':
    app.run(debug=True)
